package com.mini.cn.goods.servlet.ws.common;


import com.mini.cn.goods.io.netty.ws.WebSocketSession;
import com.mini.cn.goods.io.netty.ws.info.SessionUserInfo;
import com.mini.cn.goods.servlet.ws.WSApplicationData;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created with IntelliJ IDEA.
 * <p>
 * User: fly
 * Date: 2021-04-29
 * Time: 2:25 下午
 */
public class PushHelper {

    /**
     * 清理注册的缓存信息
     *
     * @param session
     */
    public static void clearRegisterCache(WebSocketSession session, SessionUserInfo userInfo) {
        ConcurrentHashMap<String, String> registerMsg = userInfo.getRegisterMsgMap();
        if (registerMsg == null || registerMsg.isEmpty()) {
            return;
        }
        Iterator<String> iterator = registerMsg.keySet().iterator();
        while (iterator.hasNext()) {
            String msgSceneId = iterator.next();
            ConcurrentHashMap<WebSocketSession, Boolean> list = WSApplicationData.INSTANCE.
                    getRegisterMsgMap().get(msgSceneId);
            if (list != null && !list.isEmpty()) {
                list.remove(session);
            }
        }
    }


    /**
     * 自动注册
     *
     * @param socketSession
     */
    public static void autoRegisterAllMsg(WebSocketSession socketSession, String appId) {
        String msgSceneId = String.format(LCServiceConfig.MsgSceneId.PAYSUCCESS, appId);
        //获取这个消息ID 的socket数组 加同步锁
        Map<String, ConcurrentHashMap<WebSocketSession, Boolean>> registeMap =
                WSApplicationData.INSTANCE.getRegisterMsgMap();
        ConcurrentHashMap<WebSocketSession, Boolean> list = registeMap.get(msgSceneId);
        if (list == null) {
            //如果不存在 则添加
            synchronized (registeMap) {
                if ((list = registeMap.get(msgSceneId)) == null) {
                    list = new ConcurrentHashMap<WebSocketSession, Boolean>();
                    registeMap.put(msgSceneId, list);
                }
            }
        }
        //判断在原来的关注队列中是否存在老的socket 如果有删除再添加
        //添加判断代码
        list.put(socketSession, true);
        SessionUserInfo userInfo = socketSession.getAttribute(WebSocketSession.USERKEY);
        //用户中保存自己的注册的消息  这个用户的注册消息set
        userInfo.getRegisterMsgMap().put(msgSceneId, msgSceneId);
    }

}
